<template>
  <div class="setpasswo">
    <van-nav-bar
      title="修改密码"
      left-text="返回"
      @click-left="back"
      fixed
    ></van-nav-bar>

    <van-form @submit="Reaisteruser">
      <van-field
        v-model="oldPassword"
        name="nickName"
        label="旧密码"
        placeholder="旧密码"
        :rules="PasswordRules"
      />
      <van-field
        name="password"
        :rules="PasswordRules"
        label="新密码"
        v-model="password"
        @click-right-icon="isRegister = !isRegister"
        :type="isRegister ? 'password' : 'text'"
        placeholder="新密码"
        :right-icon="isRegister ? 'closed-eye' : 'browsing-history'"
      />
      <van-button type="danger">修改</van-button>
    </van-form>
  </div>
</template>

<script>
import { Dialog } from 'vant'

import { updatePasswordAPI } from '@/api/user.js'
import { getToken, delToken } from '@/utils/storage'

export default {
  data () {
    return {
      PasswordRules: [
        {
          required: true,
          message:
            '请确保密码以字母开头，并包含至少6个（最多16个）字符，字符可以是字母、数字或下划线',
          pattern: /^[A-Za-z]\w{5,15}$/
        }
      ],
      oldPassword: '',
      password: '',
      email: '',
      isRegister: true
    }
  },
  created () {
    const tokenString = getToken()
    if (!tokenString) return this.$router.push({ name: 'Login' })
  },
  methods: {
    back () {
      this.$router.go(-1)
    },
    Reaisteruser () {
      Dialog.confirm({
        title: '确定修改',
        message: '确定修改密码'
      })
        .then(() => {
          this.setpassworld()
        })
        .catch(() => {
          // on cancel
        })
    },
    // 修改密码方法
    setpassworld () {
      const tokenString = getToken()
      if (!tokenString) return this.$router.push({ name: 'Login' })
      const data = {
        appkey: this.appkey,
        tokenString,
        password: this.password,
        oldPassword: this.oldPassword
      }
      updatePasswordAPI(data).then(res => {
        this.$toast(res.msg)
        if (res.code === 'E001') {
          delToken()
          this.$router.push({ name: 'Login' })
        }
        //
        if (res.code === 700) {
          delToken()
          this.$router.push({ name: 'Login' })
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.setpasswo {
  padding: 50px 10px 0;
  background-color: #f5f5f5;
  min-height: 100vh;
  box-sizing: border-box;
  /deep/ .van-field {
    border-bottom: 1px solid #d7d7d7;
    margin-bottom: 5px;
  }
}
/deep/ .van-button {
  left: 10%;
  width: 80%;
  background-color: #ee0a24;
  border-color: #ee0a24;
  border-radius: 20px;
  margin-top: 100px;
}
</style>
